<template>
    <div class="builder-page-container" :class="className" v-loading="loading">
        <builder-header :current-page="currentPage" :is-router-enter="isRouterEnter" :page-type="pageType" v-on="$listeners"
                        @showCompMarket="handleShowCompMarket" @showPageSetting="handlePageSetting"
                        @lowcode-change="handleLowcodeChange"></builder-header>
        <div class="page-builder-container" ref="bbody" @click="cancelSel($event)">
            <!--<builder-menu :page-type="pageType" :items="items"
                          @pinMenuChange="handlePinMenuChange" @menuDrag="handleMenuDrag" @menuDragend="handleMenuDragend"
                          :is-edit-item="isEditItem" :dataset="dataset"
                          :elem-nodes="elemNodes" :in-pin-menu="pinMenu" :current-item-el-code="currentItemElCode"
                          :current-item="currentItem" :current-page="currentPage" :current-items="currentItems"
                          @selectElenode="handleSelectElenode" @selectItem="handleSelectItem"
                          @node-drop-done="handleDropDone" @menu-click="handleMenuClick"></builder-menu>-->

            <div class="page-builder-body app-preview" :class="{ 'pin-prop': pinProp, 'pin-menu': pinMenu }" ref="jbody">
                <div class="ele-design-body" ref="bformbody">
                    <div class="ele-design-body-items" ref="appViewBody">
                        <div class="jzl-page jzl-page-bs" id="content" :class="[ pageTheme ]" :style="pageStyle">
                            <!--<div v-if="!items || items.length <= 0" class="page-builder-items-empty">
                                将左侧元素拖入此区域添加内容
                            </div>-->
                            <builder-item-dr v-for="(item, index) in items" :scale="scale" :key="item.page_item_code"
                                             :item="item" :items="items" :is-design="true" :vars="dataset.state" :index="index"
                                             :current-item="currentItem" :current-el-code="currentItemElCode" :hover-el-code="hoverItemElCode"
                                             @selectItem="handleSelectItem" @itemEnter="handleItemEnter" @itemLeave="handleItemLeave"
                                             @itemStateChange="handleItemStateChange"></builder-item-dr>
                        </div>
                        <resize-observer @notify="handlePageResize" />
                    </div>
                </div>

                <builder-nodes v-if="ready" :page-type="pageType" :items="items" :page-width="pageWidth" :page-height="pageHeight"
                               :is-edit-item="isEditItem" :dataset="dataset" :lowcode="lowcode"
                               :elem-nodes="elemNodes" :in-pin-menu="pinMenu" :current-item-el-code="currentItemElCode"
                               :current-item="currentItem" :current-page="currentPage" :current-items="currentItems"
                               @hoverElenode="handleHoverElenode" @selectElenode="handleSelectElenode" @selectItem="handleSelectItem" @changeElemNodes="initElemNodes"
                               @create-page-item="handleMenuClick" @eleNodeTreeChange="initElemNodes" @node-drop-done="handleDropDone"
                               @pinPropChange="handlePinPropChange" @pinMenuChange="handlePinMenuChange"></builder-nodes>

            </div>
            <!--<builder-prop :page-type="pageType" :is-edit-item="isEditItem" :current-item-el-code="currentItemElCode"
                          :elem-nodes="elemNodes" :items="items" :in-pin-prop="pinProp"
                          :current-item="currentItem" :current-page="currentPage" :current-items="currentItems"
                          @selectElenode="handleSelectElenode" @selectItem="handleSelectItem" @pinPropChange="handlePinPropChange"></builder-prop>-->
        </div>
    </div>
</template>

<script>
    import _ from 'lodash';
    import BuilderMixin from './builder-mixin';

    let mouseXY = {"x": null, "y": null};
    let DragPos = {"x": null, "y": null, "w": 20, /* 4 */ "h": 8, "i": null};

    export default {
        name: 'JzlPageBuilderWeb',
        mixins: [ BuilderMixin ],
        data () {
            return {
                // layoutColNum: 12,
                className: "page-builder-bs",
                isView: false,
                isH5: false,
                pageNameEditing: false,
                pageType: 1,
                scale: 0.5,
                containerLeft: 0,
                containerTop: 0,
                pageWidth: 1920,
                pageHeight: 1080
            }
        },
        components: {

        },
        async mounted () {
            this.$nextTick(() => {
                this.initScale();
            })
        },
        watch: {
            'currentPage.style._ss.width'(w) {
                this.initScale();
                // if(w && w > 0) this.pageWidth = w;
            },
            'currentPage.style._ss.height'(h) {
                this.initScale();
                // if(h && h > 0) this.pageHeight = h;
            }
        },
        computed: {
            pageStyle() {
                let style = this.$putils.getStyle(this.currentPage, "style");
                return _.assign({}, style, { scale: this.scale, left: `${ this.containerLeft }px`, top: `${ this.containerTop }px` })
            },
            /*rowHeight() {
                // 10 & 30 | 20 & 25 | 30 & 20 | 40 & 17 | 70 & 0
                let space = Number(_.get(this.currentPage, 'style.setting.space', 10));
                if(!_.isNumber(space)) {
                    space = 10;
                }
                let size = space / 2;

                return 35 - size;
            },
            layoutMargin() {
                let space = Number(_.get(this.currentPage, 'style.setting.space', 10));
                if(!_.isNumber(space)) {
                    space = 10;
                }
                let size = space / 2;
                return [ size, size ];
            },
            layoutColNum() {
                let cols = 12;
                let gridCols = _.get(this.currentPage, "grid_cols");

                if(gridCols && gridCols > 0) {
                    cols = gridCols;
                }

                return cols || 12;
            }*/
        },
        methods: {
            initScale() {
                let w = _.get(this.currentPage, 'style._ss.width');
                let h = _.get(this.currentPage, 'style._ss.height');
                if(w && w > 0) this.pageWidth = w;
                if(h && h > 0) this.pageHeight = h;

                let $el = this.$refs.appViewBody;
                let rect = $el.getBoundingClientRect();

                let width = rect.width - 20;
                let height = rect.height - 20;
                let scale = this.calculateScale(width, height);

                this.containerTop = (rect.height - this.pageHeight * scale) / 2;
                this.containerLeft = (rect.width - this.pageWidth * scale) / 2;
                this.scale = scale;
            },
            calculateScale(targetWidth, targetHeight) {
                // 计算宽度和高度的缩放比
                const widthScale = targetWidth / this.pageWidth;
                const heightScale = targetHeight / this.pageHeight;
                // 选择较小的缩放比，以确保元素能完全放入目标区域
                const scale = Math.min(widthScale, heightScale);
                return scale;
            },
            handlePageResize() {
                this.$nextTick(() => {
                    this.initScale();
                });
            },
            /*selectPage(idx) {
                if(idx < 0 || idx >= this.pages.length || idx === this.activePageIndex) {
                    return;
                }

                this.bindItem2Page();

                this.activePageIndex = idx;
                this.currentPage = this.pages[idx];
                this.items = this.pages[idx].items;

                this.showEdit(0);   // 默认选中第一个元素
            },*/
            /*drag: function (e, ele) {
                let parentRect = document.getElementById('content').getBoundingClientRect();
                let mouseInGrid = false;
                let x = e.clientX;
                let y = e.clientY;
                if (((x > parentRect.left) && (x < parentRect.right)) && ((y > parentRect.top) && (y < parentRect.bottom))) {
                    mouseInGrid = true;
                }
                if (mouseInGrid === true && (this.items.findIndex(item => item.i === 'drop')) === -1) {
                    this.items.push({
                        x: 0,   // (this.items.length * 2) % this.layoutColNum,
                        y: this.items.length + this.layoutColNum, // puts it at the bottom
                        w: Math.ceil(this.layoutColNum / 3),  // 4,
                        h: 8,
                        i: 'drop',
                    });
                }
                let index = this.items.findIndex(item => item.i === 'drop');
                if (index !== -1) {
                    try {
                        this.$refs.gridLayout.$children[this.items.length].$refs.item.style.display = "none";
                    } catch {}

                    let el = this.$refs.gridLayout.$children[index];

                    console.log(y - parentRect.top, x - parentRect.left);
                    el.dragging = { "top": y - parentRect.top, "left": x - parentRect.left};
                    let new_pos = el.calcXY(y - parentRect.top, x - parentRect.left);
                    if (mouseInGrid === true) {
                        this.$refs.gridLayout.dragEvent('dragstart', 'drop', new_pos.x, new_pos.y, 1, 1);
                        DragPos.i = String(index);
                        DragPos.x = this.items[index].x;
                        DragPos.y = this.items[index].y;
                    }
                    if (mouseInGrid === false) {
                        this.$refs.gridLayout.dragEvent('dragend', 'drop', new_pos.x, new_pos.y, 1, 1);
                        this.items = this.items.filter(obj => obj.i !== 'drop');
                    }
                }
            },*/
            /*dragend: function (e, ele) {
                console.log('------ dragend : ', e);
                let parentRect = document.getElementById('content').getBoundingClientRect();
                let mouseInGrid = false;
                let x = e.clientX;
                let y = e.clientY;

                if (((x > parentRect.left) && (x < parentRect.right)) && ((y > parentRect.top) && (y < parentRect.bottom))) {
                    mouseInGrid = true;
                }
                if (mouseInGrid === true) {
                    // alert(`Dropped element props:\n${JSON.stringify(DragPos, ['x', 'y', 'w', 'h'], 2)}`);
                    this.$refs.gridLayout.dragEvent('dragend', 'drop', DragPos.x, DragPos.y, 1, 1);
                    this.items = this.items.filter(obj => obj.i !== 'drop');
                    // UNCOMMENT below if you want to add a grid-item
                    let nitem = this._dragClone(ele, this.items);
                    nitem.x = DragPos.x;
                    nitem.y = DragPos.y;
                    nitem.w = Math.ceil(this.layoutColNum / 3); // 4;
                    nitem.h = 8;
                    nitem.alias = this._getAlias(nitem.code);
                    nitem.order = this.items.length;

                    this.items.push(nitem);

                    this.$refs.gridLayout.dragEvent('dragend', DragPos.i, DragPos.x,DragPos.y,1,1);
                    try {
                        this.$refs.gridLayout.$children[this.layout.length].$refs.item.style.display = "block";
                    } catch {}
                }
            },*/
            /*handleMarketSelectCallback(def) {
                this.handleMenuClick(def);
            },
            handleMenuDrag(info) {
                let event = _.get(info, "event");
                let ele = _.get(info, "ele");
                this.drag(event, ele)
            },
            handleMenuDragend(info) {
                let event = _.get(info, "event");
                let ele = _.get(info, "ele");
                this.dragend(event, ele)
            }*/
        }
    }
</script>

<style lang="scss" scoped>
    .page-builder-container .page-builder-body .ele-design-body .ele-design-body-items {
        top: 0px;
        bottom: 0px;
        left: 0px;
        right: 0px;
    }

    .vue-grid-layout {
        min-height: 220px;
    }
</style>
